<template>
	<el-select
		:value="value"
		placeholder="请选择考试周期"
		:multiple="multiple"
		@change="change"
	>
		<el-option
			v-for="item in endOptions"
			:key="item.pypId"
			:label="item.pypseqName"
			:value="item.pypId"
			:disabled="item.disabled"
		/>
	</el-select>
</template>

<script>
	import bdApi from "@rc/apis/bd/index.mjs";

	export default {
		props: {
			// 周期id,支持v-model
			value: {
				type: String,
				default: ""
			},
			// 完整的选中列表，元素应是包含{pypseqName,pypId}的一个对象，如果选中的对象在可选列表中找不到，则会作为一个禁用选项插入到可选列表中用于回显
			checkFullList: {
				type: Array,
				default: () => []
			},
			// 是否多选
			multiple: {
				type: Boolean,
				default: false
			},
			// 项目id
			projectId: {
				type: String,
				default: ""
			},
			// 周期年份
			pypYear: {
				type: String,
				default: ""
			},
			// 项目id是否需要必传
			isProjectRequired: {
				type: Boolean,
				default: true
			},
			// 周期年份是否需要必传
			isYearRequired: {
				type: Boolean,
				default: true
			}
		},
		data() {
			return {
				options: [] // 从后端获取的合法选项列表
			};
		},
		computed: {
			endOptions() {
				let noneItems = this.checkFullList.filter((i1) => {
					return (
						(this.value || this.value.length) &&
						(i1.pypId === this.value || this.value.some((i) => i === i1.pypId)) &&
						!this.options.some((i2) => i2.pypId === i1.pypId)
					);
				});
				noneItems = noneItems.map((i) => ({ ...i, disabled: true }));
				return [...noneItems, ...this.options];
			}
		},
		watch: {
			projectId() {
				this.queryList();
			},
			pypYear() {
				this.queryList();
			}
		},
		methods: {
			queryList() {
				// 项目不能为空
				if (!this.projectId && this.isProjectRequired) {
					this.options = [];
					return;
				}
				// 年份不能为空
				if (!this.pypYear && this.isYearRequired) {
					this.options = [];
					return;
				}
				bdApi.queryYearPeriodList({
					data: {
						projectId: this.projectId,
						pypYear: this.pypYear,
						pypAvlstatus: "Y"
					},
					success: ({ data }) => {
						this.options = data || [];
						this.$emit("ready", this.options);
					}
				});
			},
			change(data) {
				this.$emit("input", data);
				this.$emit("change", data);
			},
			api_getOptions() {
				return this.options;
			}
		},
		created() {
			this.queryList();
		}
	};
</script>
